package com.shanshan.manage.web.controller;

import com.shanshan.manage.common.annotation.Log;
import com.shanshan.manage.common.config.RuoYiConfig;
import com.shanshan.manage.common.core.controller.BaseController;
import com.shanshan.manage.common.core.domain.AjaxResult;
import com.shanshan.manage.common.core.page.TableDataInfo;
import com.shanshan.manage.common.enums.BusinessType;
import com.shanshan.manage.common.utils.SecurityUtils;
import com.shanshan.manage.common.utils.file.FileUploadUtils;
import com.shanshan.manage.common.utils.file.FileUtils;
import com.shanshan.manage.common.utils.poi.ExcelUtil;
import com.shanshan.manage.framework.config.ServerConfig;
import com.shanshan.manage.web.domain.ACustomsMsg;
import com.shanshan.manage.web.service.IACustomsMsgService;
import com.shanshan.manage.web.utils.RecognizeTableOcr;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 报关单信息Controller
 *
 * @author zhaoShuHeng
 * @date 2023-08-29
 */
@RestController
@RequestMapping("/aCustomsMsg/aCustomsMsg")
public class ACustomsMsgController extends BaseController {
    @Autowired
    private IACustomsMsgService aCustomsMsgService;

    @Autowired
    private RecognizeTableOcr recognizeTableOcr;

    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询报关单信息列表
     */
    @PreAuthorize("@ss.hasPermi('aCustomsMsg:aCustomsMsg:list')")
    @GetMapping("/list")
    public TableDataInfo list(ACustomsMsg aCustomsMsg) {
        startPage();
        List<ACustomsMsg> list = aCustomsMsgService.selectACustomsMsgList(aCustomsMsg);
        return getDataTable(list);
    }

    /**
     * 导出报关单信息列表
     */
    @PreAuthorize("@ss.hasPermi('aCustomsMsg:aCustomsMsg:export')")
    @Log(title = "报关单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ACustomsMsg aCustomsMsg) {
        List<ACustomsMsg> list = aCustomsMsgService.selectACustomsMsgList(aCustomsMsg);
        ExcelUtil<ACustomsMsg> util = new ExcelUtil<ACustomsMsg>(ACustomsMsg.class);
        util.exportExcel(response, list, "报关单信息数据");
    }

    /**
     * 获取报关单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('aCustomsMsg:aCustomsMsg:query')")
    @GetMapping(value = "/{customsId}")
    public AjaxResult getInfo(@PathVariable("customsId") Long customsId) {
        return success(aCustomsMsgService.selectACustomsMsgByCustomsId(customsId));
    }

    /**
     * 新增报关单信息
     */
    @PreAuthorize("@ss.hasPermi('aCustomsMsg:aCustomsMsg:add')")
    @Log(title = "报关单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ACustomsMsg aCustomsMsg) {
        int i = aCustomsMsgService.insertACustomsMsg(aCustomsMsg);
        if (i==10086){
            return AjaxResult.error("该提单信息已录入，请勿重复录入");
        }
        return toAjax(i);
    }

    /**
     * 自动识别报关单
     * @param map
     * @return
     */
    @PostMapping("/autoAddCustomsMsg")
    public AjaxResult AutoAddCustomsMsg(@RequestBody Map<String,String> map){
        try {
            String pdfUrl = map.get("url");
            String filePath = RuoYiConfig.getUploadPath();
            String fileUrl = filePath + pdfUrl.replace("/profile/upload","");
            PDDocument document = PDDocument.load(new File(fileUrl));
            // Create a PDF renderer
            PDFRenderer renderer = new PDFRenderer(document);

            BufferedImage image = renderer.renderImageWithDPI(0, 300);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            baos.flush();
            byte[] bytes = baos.toByteArray();
            MultipartFile multipartFile = new MockMultipartFile("file", fileUrl.substring(fileUrl.lastIndexOf("/")), "image/png", bytes);
            // Close the document
            document.close();

            // 上传文件路径
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, multipartFile);
            String url = filePath + fileName.replace("/profile/upload","");
            FileInputStream fileInputStream = new FileInputStream(url);
            ACustomsMsg aCustomsMsg = recognizeTableOcr.orc(fileInputStream);
            aCustomsMsg.setFilePath(pdfUrl);
//            int id = aCustomsMsgService.insertACustomsMsg(aCustomsMsg);
            return AjaxResult.success(aCustomsMsg);
        }  catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 修改报关单信息
     */
    @PreAuthorize("@ss.hasPermi('aCustomsMsg:aCustomsMsg:edit')")
    @Log(title = "报关单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ACustomsMsg aCustomsMsg) {
        return toAjax(aCustomsMsgService.updateACustomsMsg(aCustomsMsg));
    }

    /**
     * 删除报关单信息
     */
    @PreAuthorize("@ss.hasPermi('aCustomsMsg:aCustomsMsg:remove')")
    @Log(title = "报关单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{customsIds}")
    public AjaxResult remove(@PathVariable Long[] customsIds) {
        return toAjax(aCustomsMsgService.deleteACustomsMsgByCustomsIds(customsIds));
    }
}
